package com.ksj.Utils.DataSorting;

import com.ksj.Service.MainService;
import com.ksj.Utils.MqttTool.MqttTool;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;


public class DataSortingTool {
    private static org.slf4j.Logger LOG = LoggerFactory.getLogger(DataSortingTool.class);

    public static void DataSorting(String data) {
        //判断数据结构是List还是Map


        try {
            String prefix = data.substring(0, 1);
            if ("[".equals(prefix)) {
                JSONArray arr = new JSONArray(data);
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    handleData(obj.toString());
                }
            } else if ("{".equals(prefix)) {
                handleData(data);
            }
        }catch (JSONException jsonError){
            LOG.error("data-sorting接受数据格式错误！",jsonError);
        }catch (StringIndexOutOfBoundsException stringError){
            LOG.error("data-sorting接受数据为空！",stringError);
        }


    }

    public static void handleData(String data){
        JSONObject obj = new JSONObject(data);
        //根据flag判断处理数据的队列
        String flag = String.valueOf(obj.get("Flag"));
        if ("Z".equals(flag)){
           MqttTool.sendQueueMsg("common",data);
        }else if ("T".equals(flag)){
            MqttTool.sendQueueMsg("transaction",data);
        }else if ("A".equals(flag)){
           MqttTool.sendQueueMsg("alarm",data);
        }
    }


}
